# -*- coding: utf-8 -*-
import codecs
from django.core.urlresolvers import reverse
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response
from catalogs.davilki import Davilki

def view(request):
    if not request.user.is_authenticated():
        return HttpResponseRedirect(reverse('login'))
    if request.user.is_superuser:
        return render_to_response('catalogs/view.html')
    return HttpResponseRedirect(reverse('home'))


def davilki(request):
    if not request.user.is_authenticated():
        return HttpResponseRedirect(reverse('login'))
    if request.user.is_superuser:
        if request.method == 'GET':
            if request.GET.has_key('davilka'):
                davilki = Davilki()
                data = HttpResponse(mimetype='text/csv')
                data['charset'] = 'cp1251'
                if request.GET['davilka'] == 'nadavi':
                    data['Content-Disposition'] = 'attachment; filename="nadavi.csv"'
                    if request.GET.has_key('name'):
                        davilki.setProductsByFiltr(request.GET)
                    else:
                        davilki.setProducts()
                    data = davilki.createPriceForNadavi(data)
                elif request.GET['davilka'] == 'hotline':
                    data['Content-Disposition'] = 'attachment; filename="hotline.csv"'
                    if request.GET.has_key('name'):
                        davilki.setProductsByFiltr(request.GET)
                    else:
                        davilki.setProducts()
                    data = davilki.createPriceForHotline(data)
                elif request.GET['davilka'] == 'priceua':
                    data['Content-Disposition'] = 'attachment; filename="priceua.csv"'
                    if request.GET.has_key('name'):
                        davilki.setProductsByFiltr(request.GET)
                    else:
                        davilki.setProducts()
                    data = davilki.createPriceForPriceua(data)
                data.content = codecs.decode(data.content, 'utf-8', 'replace').encode('cp1251', 'ignore')
                return data
        return render_to_response('catalogs/view.html')
    return HttpResponseRedirect(reverse('home'))